<template>
    <div class="chat" v-if="friendId">
        <div class="header">
            <div>{{ data.friendName }} </div>
            <div class="ls" @click="showDiaLog()">历史聊天</div>
        </div>
        <div class="container" v-loading="loading">
            <el-scrollbar ref="scrollbarRef" height="100%">
                <TransitionGroup class="container" tag="ul" name="list">
                    <div v-for="item, index in newsList" class="text" :key="item.id">
                        <div style="width: 100%;display: flex; justify-content: center;">
                            <div class="times"
                                v-if="new Date(item.sendTime).getTime() >= showTime ? showTime = new Date(item.sendTime).getTime() + 300000 : false">
                                {{ time(new Date(item.sendTime)) }}
                            </div>
                        </div>
                        <div class="contaiers" v-if="+item.sendUserId != store.user.id">

                            <img lazy :src="item.sendUserImageUrl" alt="">

                            <div class="conent">
                                {{ item.content }}
                            </div>
                        </div>
                        <div class="contaiers" style="justify-content: flex-end;" v-else-if="!item.exception">

                            <el-popconfirm width="220" v-if='Date.now() - new Date(item.sendTime).getTime() <= 120000'
                                confirm-button-text="OK" cancel-button-text="NO" @confirm="confirmEvent(item!.id, index)"
                                icon-color="#626AEF" title="确定要撤回消息吗">
                                <template #reference>
                                    <div class="conent use">
                                        {{}}
                                        {{ item.content }}
                                    </div>
                                </template>
                            </el-popconfirm>
                            <div v-else class="conent use">
                                {{}}
                                {{ item.content }}
                            </div>
                            <img lazy :src="item.sendUserImageUrl" alt="">

                        </div>
                        <div v-else class="ds">
                            {{ item.exception }}
                        </div>
                    </div>
                </TransitionGroup>
            </el-scrollbar>
        </div>

        <div class="textarea">
            <el-input class="input" style="height: 70%; overflow: hidden;" v-model="textarea" :rows="2" type="textarea"
                placeholder="把你想说的告诉他吧" />
            <el-button class="sucess" type="success" @click="send">发送</el-button>
        </div>
        <teleport to="body">
            <el-dialog v-model="dialogTableVisible" title="历史记录">
                <div style="display: flex; margin-bottom: 1vh;">
                    <el-input v-model="keyword" placeholder="搜索关键字" />
                    <el-button style="margin-left: 2vw;" @click="clickKeyword" type="primary">搜索&重置</el-button>
                </div>
                <div class="infinite-list-wrapper" style="overflow: auto">
                    <div v-infinite-scroll="load" class="list" :infinite-scroll-disabled="disabled">
                        <div class="list-item Listcontainer" v-for="item in lisjl" :key="item.id">
                            <div class="user">
                                <img :src="item.sendUserImageUrl" alt="">
                                <div class="title">
                                    <div>{{ item.sendUserName }}</div>
                                    <div>{{ item.content }}</div>
                                </div>
                                <div class="time">
                                    {{ time(new Date(item.sendTime)) }}
                                </div>
                            </div>

                        </div>
                    </div>

                    <p v-if="loadings">加载中...</p>
                    <p v-if="noMore">没有记录啦</p>
                </div>
            </el-dialog>
        </teleport>
    </div>
</template>

<script lang="ts" setup>
import { ElScrollbar, ElMessage } from 'element-plus'
import { ref, watchEffect, reactive, nextTick, computed } from "vue"
import { useWebSocket, time, dateStringify } from '@/hooks/index'
import { showRecentNews, updateReadStatus, deleteNews, pageNews } from '@/request/api'
import type { frientDatum, Listss } from '@/type/friend'
import { useStore } from '@/stores/counter'
const store = useStore()
// document.createElement
// let ac:HTMLDivElement=document.querySelector("div") as HTMLDivElement
// ac.children()
//用户聊天历史记录
const loadings = ref(false)
const noMore = ref(false)
const disabled = computed(() => loadings.value || noMore.value)
const keyword = ref<string>('')
let pageIndex = 1
//点击搜索按钮，搜索聊天历史
const clickKeyword = () => {
    showDiaLog()
    load()
    keyword.value = ''
}
const load = () => {
    loadings.value = true
    pageNews<{
        userId: string,
        startTime: Date,
        endTime: string,
        pageSize: number,
        pageIndex: number,
        keyword: string
    }>({
        userId: data.friendId,
        startTime: new Date(0),
        endTime: dateStringify(new Date()),
        pageSize: 10,
        pageIndex,
        keyword: keyword.value
    }).then(res => {
        loadings.value = false
        pageIndex++
        lisjl.push(...res.data.list)
        if (res.data.list.length < 10)
            noMore.value = true
    })
}
let dialogTableVisible = ref<boolean>(false)      //历史记录的聊天框
let lisjl = reactive<Listss[]>([])
//打开聊天弹窗
const showDiaLog = () => {
    dialogTableVisible.value = true
    lisjl.length = 0
    noMore.value = false
    pageIndex = 1
    loadings.value = false
}



let data = defineProps<{
    friendId: string,           //聊天用户的id
    friendName: string     //聊天的用户
}>()
let loading = ref<boolean>(false)     //loading
let showTime = 0
watchEffect(() => {                 //1点击不同好友发送好友历史聊天请求，2打开loading，3返回请求后关闭loading将滚动移动到最下方
    if (data.friendId) {
        loading.value = true
        showRecentNews<string>(data.friendId).then(res => {
            loading.value = false

            newsList.length = 0
            if (res.data.length == 0)
                return
            
            newsList.push(...res.data)
            showTime = (new Date(newsList[0].sendTime)).valueOf()

            //返回请求后关闭loading将滚动移动到最下方
            nextTick(() => {
                scrollbarRef.value!.setScrollTop(9000)

            })
            updateReadStatus<string>(data.friendId)
        })

    }

}, {
    flush: "post",

})

let newsList = reactive<frientDatum[]>([])       //消息列表
let textarea = ref<string>('')
let classify: any = {}
const message = (e: any) => {
    console.log(e);
    

    if (e instanceof Array) return
    if (e.type == "NEWS" && data.friendId == e.sendUserId || e.sendUserId == store.user.id) {
        if(!e.id){
            ElMessage.error('消息达到上限,请等待回复')
            return
        }
        newsList.push(e)
        nextTick(() => {
            scrollbarRef.value!.setScrollTop(9000)
            loading.value = false
        })
    }
}

let ws = useWebSocket('chat', message)
const send = () => {
    if(textarea.value==''){
        return   ElMessage.error('请输入内容')
    }
    let ac = JSON.stringify(
        {
            sendId: store.user.id,
            acceptId: data.friendId,
            content: textarea.value
        })

    textarea.value = ''
    ws.send(ac)

}
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()
const confirmEvent = (id: number, index: number) => {
    deleteNews(id).then(res => {
        return res.data ? Promise.resolve(res.data) : Promise.reject(res.msg)
    }).then((res: string) => {
        ElMessage({
            message: res,
            type: 'success',
        })
        newsList.splice(index, 1)
    }).catch(err => {
        ElMessage.error(err)
    })
}

</script>

<style lang=less  scoped>
.chat {
    flex: 1;
    color: @color;
    background-color: @backColor;

    >div {
        padding-left: 0.8vw;
        width: calc(100% - 0.8vw);
        border-bottom: 1px solid #E7E7E7;
    }
}

.header {
    height: 10%;
    .flexAc();
    justify-content: space-between;
    font-size: 1.4vw;
}

:deep(.el-textarea__inner) {
    resize: none;
}

:deep(.el-textarea__inner:focus) {
    box-shadow: 0 0 0 1px #F5F5F5 inset;

}

:deep(.el-textarea__inner) {
    height: 100%;
    background-color: @backColor;
    border: 0px;

    box-shadow: none;
}

.textarea {
    position: relative;
    height: 20%;
    display: flex;
    flex-direction: column;

    border-bottom: 0px !important;

    .sucess {
        align-self: flex-end;
        margin-right: 3vw;
        width: 5vw;
        height: 3vh;
        aspect-ratio: 1/1;
    }
}

.container {
    height: 70%;

    width: calc(100% - 3.1vw) !important;
    padding-right: 2vw;
    margin-left: 0.3vw;

    img {
        width: 50px;
        aspect-ratio: 1/1;
    }

    .text {
        .times {
            background-color: #DADADA;
            font-size: 0.9vw;
            color: #FFFFFF;
            display: inline-block;
            padding: 0.2vw;
            border-radius: 2px;
            margin: 0px auto;

        }

        // overflow: hidden;
        width: 100%;
        padding: 2vh 0px;

        .contaiers {
            .flexAc();
        }

        .conent {
            max-width: 60%;
            padding: 10px 10px;

            margin-left: 1vw;
            flex-wrap: wrap;
            .flexAc();
            color: #000 !important;
            background-color: #FFFFFF;
            border-radius: 10px;
            filter: drop-shadow(0px 0px 2px rgba(206, 206, 206, 0.842));
            position: relative;
            word-wrap: break-word;
            word-break: break-all;


        }

        .use {
            margin-right: 1vw;
            background-color: #95EC69;
        }

        .conent::before {
            content: '';
            z-index: 10;
            position: absolute;
            top: 50%;
            left: 0px;
            width: 10px;
            transform: translate(-50%, -50%) rotate(45deg);
            height: 10px;
            display: block;
            background-color: #FFFFFF;
        }

        .use::before {
            background-color: #95EC69;
            left: 100%;

        }
    }

}

.container {
    position: relative;
    padding: 0;
}

.infinite-list-wrapper {
    height: 50vh;
    text-align: center;
}

.infinite-list-wrapper .list {
    padding: 0;
    margin: 0;
    list-style: none;
}

.infinite-list-wrapper .list-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    background: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
}

.infinite-list-wrapper .list-item+.list-item {
    margin-top: 10px;
}

.Listcontainer {
    width: 95%;
    margin: 2vh;
    padding: 2vh 0px;
    border-bottom: 1px solid #d3d3d3b7;
    .flexAc();
    justify-content: space-between;

    .user {
        height: 100%;
        .flexAc();
        width: 100%;

        .time {
            margin-left: 2vw;
        }

        img {
            width: 50px;
            aspect-ratio: 1/1;
            border-radius: 5px;
        }

        .title {
            margin-left: 10px;
            display: flex;
            flex: 1;
            height: 50px;
            align-content: space-between;
            flex-wrap: wrap;
            position: relative;

            >div {
                position: absolute;
                width: 100%;
                text-align: left;
                .textNOLine();
            }

            >div:nth-child(2) {
                bottom: 0px;
            }
        }
    }
}

.item {
    width: 100%;
    height: 30px;
    background-color: #f3f3f3;
    border: 1px solid #666;
    box-sizing: border-box;
}

.list-move,
/* 对移动中的元素应用的过渡 */
.list-enter-active,
.list-leave-active {
    transition: all 0.5s ease;
}

.list-enter-from,
.list-leave-to {
    opacity: 0;
    transform: translateX(30px);
}


/* 确保将离开的元素从布局流中删除
  以便能够正确地计算移动的动画。 */
.list-leave-active {
    position: absolute;
}

// .list-enter-active,
// .list-leave-active {
//   transition: all 0.5s ease;
// }
// .list-enter-from,
// .list-leave-to {
//   opacity: 0;
//   transform: translateX(30px);
// }
.ls {
    font-size: 0.8vw;
    cursor: pointer;
    margin-right: 10px;
}

.ls::after {
    content: ' ';
    display: block;
    height: 1px;
    background-color: #000;
    transition: all 0.3s ease-in-out;
    transform: scale(0);
    transform-origin: left;

}

.ls:hover::after {
    transform: scale(1);
}

.ds {
    font-size: 0.8vw;
    color: #777777;
    text-align: center;
}
</style>